/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fsd.semana2.aula.echoselector;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;

/**
 *
 * @author nfsa
 */
public class EchoSelectorServerMain {

    public static void echoServerMain() throws Exception
    {
        ServerSocketChannel ssocket = SelectorProvider.provider().openServerSocketChannel();
        ssocket.configureBlocking(false);
        ssocket.socket().bind(new InetSocketAddress(12345));

        Selector selector = Selector.open();
        ssocket.register(selector, SelectionKey.OP_ACCEPT);

        while (selector.isOpen())
        {
            selector.select();
            for (SelectionKey key : selector.selectedKeys())
            {
                if (key.isAcceptable())
                {
                    SocketChannel socket = ssocket.accept();
                    socket.configureBlocking(false);
                    socket.register(selector, SelectionKey.OP_READ);
                }
                if (key.isWritable())
                {
                    SocketChannel socket = (SocketChannel) key.channel();
                    ByteBuffer output = (ByteBuffer) key.attachment();
                    socket.write(output);
                    key.interestOps(SelectionKey.OP_READ);
                }
                if (key.isReadable())
                {
                    SocketChannel socket = (SocketChannel) key.channel();
                    ByteBuffer input = ByteBuffer.allocate(100);
                    if (socket.read(input) <= 0)
                    {
                        key.cancel();
                        socket.close();
                    }
                    else
                    {
                        input.flip();
                        key.attach(input);
                        key.interestOps(SelectionKey.OP_WRITE);
                    }
                }
            }
            selector.selectedKeys().clear();
        }
    }
}
